<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/8/5
 * Time: 14:31
 */

namespace app\service;

use phpmailer\BaseException;
use think\Db;

/**
 * 购买服务层
 * @author   juzi
 * @blog    https://blog.csdn.net/juziaixiao
 * @version 1.0.0
 * @date    2020年8月5日14:30:00
 */
class BuyService
{
    /**
     * 购物车添加
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年8月5日14:30:00
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function CartAdd($params = [])
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'bizpro_id',
                'error_msg'         => '商品id有误',
                'error_code' => 3002,
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'buy_num',
                'error_msg'         => '购买数量有误',
                'error_code' => 3003,
            ],
            [
                'checked_type'      => 'min',
                'key_name'          => 'buy_num',
                'checked_data'      => 1,
                'error_msg'         => '购买数量有误',
                'error_code' => 3003,
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'member',
                'error_msg'         => '用户信息有误',
                'error_code' => 3004,
            ],
        ];

        $ret=ParamsChecked($params, $p);

        if(true !== $ret)
        {
            $error_arr = explode(',', $ret);

            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }



        // 获取商品
        $bizpro_id = intval($params['bizpro_id']);
        $bizpro = Db::name('bizpro')->where(['id'=>$bizpro_id, 'status'=>1, ])->find();

        if(empty($bizpro))
        {

            throw new BaseException(['code'=>403 ,'errorCode'=>3005,'msg'=>'商品不存在或已删除','status'=>false,'debug'=>false ]);

        }
        // 规格处理
        $spec=[];
        if(isset($params['standard_value1']) and  !empty($params['standard_value1']))
        {
            $spec['standard_value1'] =  $params['standard_value1'];
        }
        if(isset($params['standard_value2']) and  !empty($params['standard_value2']))
        {
            $spec['standard_value2'] =  $params['standard_value2'];
        }
        // 获取商品基础信息
        $data_params = [
            'where' => ['b.id'=>$params['bizpro_id']],
            'page' => false,
            'field' => 'b.supplier_id,b.old_price,b.id b_id,b.name b_name,b.label,b.imgurl,b.old_price,b.standard_base,sd.standard_desc,b.express_price',
        ];

        $re =BizproService::BizproList($data_params);
        #价格查询
        $sale_price=BizproService::StandardPrice(
            [
                'standard_value1'=>$spec['standard_value1'],
                'standard_value2'=>$spec['standard_value2'],
                'bizpro_id'=>$bizpro_id
            ]
        );
        // 添加购物车
        $data = [
            'member_id'       => $params['member']['id'],
            'bizpro_id'       => $bizpro_id,
            'bizpro_name'         => $re['data'][0]['b_name'],
            'supplier_id'         => $re['data'][0]['supplier_id'],
            'bizpro_label'         => json_encode($re['data'][0]['label']),
            'bizpro_imgurl'        => $re['data'][0]['imgurl'],
            'bizpro_oldprice'      =>  $re['data'][0]['old_price'],
            'bizpro_saleprice'         =>$sale_price['data']['sale_price'],
            'buy_num'         => intval($params['buy_num']),
            'bizpro_spec_value'          => empty($spec) ? '' : json_encode($spec),
        ];

        // 存在则更新
        $where = [
            'member_id'=>$data['member_id'],
            'bizpro_id'=>$data['bizpro_id'],
            'bizpro_spec_value'=>$data['bizpro_spec_value']
        ];

        $temp = Db::name('member_cart')->where($where)->find();
//        var_($temp);die;

        if(empty($temp))
        {

            if(Db::name('member_cart')->insertGetId($data) > 0)
            {
                return DataReturn('加入成功', 0);
            }
        } else {

            if($params['mark']=='detail')
            {
                Db::name('member_cart')->where($where)->setInc('buy_num',intval($params['buy_num'])) ;
                return DataReturn('修改成功', 0);
            }
            Db::name('member_cart')->where($where)->update(array('buy_num'=>$params['buy_num'])) ;
            return DataReturn('修改成功', 0);
        }


        throw new BaseException(['code'=>403 ,'errorCode'=>3001,'msg'=>'保存失败','status'=>false,'debug'=>false ]);

    }


    /**
     * 获取购物车列表
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年8月5日14:30:00
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function CartList($params = [])
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'member_id',
                'error_msg'         => '用户信息有误',
                'error_code'        => 3004,
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }
        $where = (!empty($params['where']) && is_array($params['where'])) ? $params['where'] : [];
        $where['c.member_id'] = $params['member_id'];
        $data = Db::name('member_cart')->alias('mc')->leftJoin(['bizpro'=>'b'],'b.id=mc.bizpro_id')
            ->where(['member_id'=>$params['member_id']])->field("mc.*,b.status")->order('mc.id desc')->select();
        // 数据处理
        if(!empty($data))
        {
            $del=[];
            $k=0;
            foreach($data as &$v)
            {
                // 规格
                $v['bizpro_spec_value'] = empty($v['bizpro_spec_value']) ?[] : json_decode($v['bizpro_spec_value'], true);
                $v['bizpro_spec_value1']='';
                $v['bizpro_spec_value2']='';

                if(!empty($v['bizpro_spec_value']))
                {
                    $v['bizpro_spec_value1']=isset($v['bizpro_spec_value']['standard_value1'])?$v['bizpro_spec_value']['standard_value1']:'';
                    $v['bizpro_spec_value2']=isset($v['bizpro_spec_value']['standard_value2'])?$v['bizpro_spec_value']['standard_value2']:'';
                }

               // $v['bizpro_spec_value']=empty($v['bizpro_spec_value']) ? '' : join('',$v['bizpro_spec_value']);
                $v['bizpro_imgurl'] = ResourceService::AttachmentPathViewHandle($v['bizpro_imgurl']);
                $v['bizpro_label']=empty($v['bizpro_label']) ? '' : json_decode($v['bizpro_label'], true);

                if($v['status']!=1)
                {
                 $del[$k]=$v['id'];
                }
                $k=$k+1;
            }

            # 删除脏数据
            if(count($del)>0)
            {
             // Db::name('member_cart')-> where([['id','in',$del]])->delete();
            }

        }

        return DataReturn('获取成功', 0, $data);
    }


    /**
     * 购物车删除
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年8月5日14:30:00
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function CartDelete($params = [])
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'id',
                'error_msg'         => '删除数据id有误',
                'error_code'        => 3006,
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'member',
                'error_msg'         => '用户信息有误',
                'error_code'        => 3004,
            ],
        ];
        $ret = ParamsChecked($params, $p);

        if(true !== $ret)
        {
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }

        // 查询用户状态是否正常
         MemberService::MemberStatusCheck('id', $params['member']['id']);


        // 删除
        $where = [
            'id'        => explode(',', $params['id']),
            'member_id'   => $params['member']['id']
        ];
        if(Db::name('member_cart')->where($where)->delete())
        {
            return DataReturn('删除成功', 0);
        }
        return DataReturn('删除失败或资源不存在', -100);

        throw new BaseException(['code'=>403 ,'errorCode'=>'3007','msg'=>'删除失败或资源不存在','status'=>false,'debug'=>false ]);

    }
}